package cn.stylefeng.guns.modular.yingbao.service.impl;

import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.yingbao.entity.SysUser;
import cn.stylefeng.guns.modular.yingbao.entity.UserMy;
import cn.stylefeng.guns.modular.yingbao.entity.UserName;
import cn.stylefeng.guns.modular.yingbao.mapper.SysUserMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserMyMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserNameMapper;
import cn.stylefeng.guns.modular.yingbao.model.params.UserNameParam;
import cn.stylefeng.guns.modular.yingbao.model.result.UserNameResult;
import  cn.stylefeng.guns.modular.yingbao.service.UserNameService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 实名认证表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2019-12-11
 */
@Service
public class UserNameServiceImpl extends ServiceImpl<UserNameMapper, UserName> implements UserNameService {
    @Resource
    SysUserMapper sysUserMapper;

    @Override
    public void add(UserNameParam param){
        UserName entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(UserNameParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(UserNameParam param){
        UserName oldEntity = getOldEntity(param);
        UserName newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public UserNameResult findBySpec(UserNameParam param){
        return null;
    }

    @Override
    public List<UserNameResult> findListBySpec(UserNameParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(UserNameParam param){
        Page pageContext = getPageContext();
        if(param.getId() == null){
            IPage status = this.baseMapper.selectPage(pageContext, new QueryWrapper<UserName>().orderByAsc("status"));
            return LayuiPageFactory.createPageInfo(status);
        }
        //UserMy userMy = userMyMapper.selectById(param.getId());
        //UserMy userMy = userMyMapper.selectOne(new QueryWrapper<UserMy>().eq("id", param.getId()));
        SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("referrer_code", Long.valueOf(param.getId())));
        if(sysUser == null){
            return null;
        }
        IPage status = this.baseMapper.selectPage(pageContext, new QueryWrapper<UserName>().like("userid",sysUser.getId()));
        return LayuiPageFactory.createPageInfo(status);
    }

    @Override
    public ResponseData addUserName(UserName userName) {
        UserName userName1 = this.baseMapper.selectOne(new QueryWrapper<UserName>().eq("userid", userName.getUserid()).eq("backup1", "0"));
        if(userName1 != null){
            return ResponseData.error(500,"您有正在审核的记录");
        }
        if(StringUtils.isEmpty(userName.getIdentity())) {
            return ResponseData.error(500,"身份证不能为空");
        }
        if (userName.getIdentity().length() != 18) {
            return ResponseData.error(500, "请输入正确的身份证号码");
        }
        if(StringUtils.isEmpty(userName.getJustpic()) || StringUtils.isEmpty(userName.getAgainstpic())){
            return ResponseData.error(500,"正反照都需要偶");
        }
        if(StringUtils.isEmpty(userName.getJustpic()) && StringUtils.isEmpty(userName.getAgainstpic())){
            SysUser sysUser = sysUserMapper.selectById(userName.getUserid());
            List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("phone", sysUser.getPhone()));
            for(SysUser user:userList){
                UserName userid = this.baseMapper.selectOne(new QueryWrapper<UserName>().eq("userid", user.getId()));
                if(!StringUtils.isEmpty(userid.getAgainstpic()) && !StringUtils.isEmpty(userid.getJustpic())){
                    userName.setAgainstpic(userid.getAgainstpic());
                    userName.setJustpic(userid.getJustpic());
                    break;
                }
            }
        }
        userName.setStatus(0);
        userName.setBackup1("0");
        userName.setBackup2("0");
        userName.setBackup3("0");
        userName.setBackup4("0");
        userName.setBackup5("0");
        int insert = this.baseMapper.insert(userName);
        if(insert > 0){
            return ResponseData.success(200,"添加成功",null);
        }
        return ResponseData.error(500,"添加失败");
    }

    @Override
    public ResponseData queryByUserId(String userid) {
        UserName username = this.baseMapper.selectOne(new QueryWrapper<UserName>().eq("userid", userid));
        if(username != null){
            if(username.getStatus() == 0) {
                return ResponseData.success(200, "实名认证等待审核", null);
            }else if(username.getStatus() == 1){
                return ResponseData.success(400,"实名认证通过",null);
            }else if(username.getStatus() == 2){
                this.baseMapper.deleteById(username.getId());
                return ResponseData.error(405,"审核未通过,请重新添加");
            }else{
                return ResponseData.error(500,"未知错误");
            }
        }
        return ResponseData.success(500,"您还没实名认证",null);
    }

    @Override
    public ResponseData queryByPhone(String phone) {
        Integer x = 0;
        List<SysUser> userList = sysUserMapper.selectList(new QueryWrapper<SysUser>().eq("phone", phone));
        for(SysUser sys : userList){
            UserName userid = this.baseMapper.selectOne(new QueryWrapper<UserName>().eq("userid", sys.getId()).eq("status","1"));
            if(userid != null && !StringUtils.isEmpty(userid.getJustpic()) && !StringUtils.isEmpty(userid.getAgainstpic())){
                x++;
            }
        }
        if(x > 0){
            return ResponseData.success(200,"无需正反照",null);
        }
        return ResponseData.error(500,"上传正反照");
    }

    /*@Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData upStatus(UserName username) {
        username.setStatus(1);
        int i = this.baseMapper.update(username,new QueryWrapper<UserName>().eq("userid",username.getUserid()));
        if(i > 0){
            SysUser sysUser = new SysUser();
            sysUser.setId(username.getUserid());
            sysUser.setAuthenticationId(1L);
            sysUserMapper.updateById(sysUser);
            return ResponseData.success(200,"修改成功",null);
        }
        return ResponseData.error(500,"修改失败");
    }*/

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData upStatus(String id,String status) {
        UserName userName = this.baseMapper.selectById(id);
        if(userName.getStatus() != 0){
            return ResponseData.error(500,"该用户已经审核过了");
        }
        userName.setStatus(Integer.parseInt(status));
        int i = this.baseMapper.update(userName,new QueryWrapper<UserName>().eq("id",userName.getId()));
        if(i > 0){
            if(1 == userName.getStatus()) {
                SysUser sysUser = new SysUser();
                sysUser.setId(userName.getUserid());
                sysUser.setAuthenticationId(1L);
                sysUserMapper.updateById(sysUser);
            }
            return userName.getStatus() == 1? ResponseData.success(200,"审核通过",null) : ResponseData.success(200,"审核不通过",null);
        }
        return ResponseData.error(500,"修改失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData delById(String id) {
        UserName userName = this.baseMapper.selectById(id);
        SysUser sysUser = this.sysUserMapper.selectById(userName.getUserid());
        sysUser.setAuthenticationId(0L);
        sysUser.setVersion(sysUser.getVersion()+1);
        this.sysUserMapper.update(sysUser, new QueryWrapper<SysUser>().eq("id", sysUser.getId()));
        int i = this.baseMapper.deleteById(id);
        if(i > 0){
            return ResponseData.success(200,"删除成功",null);
        }
        return ResponseData.error(500,"删除失败");
    }

    /**
     * 上传文件（自定义路径）
     *
     * @author fengshuonan
     * @Date 2019-05-04 17:18
     */


    private Serializable getKey(UserNameParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private UserName getOldEntity(UserNameParam param) {
        return this.getById(getKey(param));
    }

    private UserName getEntity(UserNameParam param) {
        UserName entity = new UserName();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
